<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>大文件上传</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js"></script>
  </head>
  <body>
    <form action="" id="FormUpload">
      <p id="percent">上传进度 0%</p>
      <input type="file" id="inputUpload" />
      <button type="submit">提交</button>
    </form>
    <script>
      const form = document.getElementById('FormUpload')
      const ipt = document.getElementById('inputUpload')
      let file // 待上传的文件
      let uploadPercent = 0 // 上传进度百分比
      ipt.addEventListener('change', function (e) {
        file = e.target.files[0]
      })

      form.addEventListener('submit', async function (e) {
        e.preventDefault()
        let size = 2 * 1024 * 1024 // 设置切片大小 2M
        let fileSize = file.size // 文件大小

        // 分多少块切片
        let totalChunks = Math.ceil(fileSize / size)

        for (let i = 0; i < totalChunks; i++) {
          let start = i * size
          let end = Math.min(start + size, fileSize)
          let chunk = file.slice(start, end) // 待上传的切片文件
          let formData = new FormData()
          formData.append('file', chunk)
          formData.append('chunkIndex', i)
          formData.append('totalChunks', totalChunks)
          // 向后端发送请求
          await axios.post('/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            },
            //axios提供的监测请求进度的api
            onUploadProgress: function (progressEvent) {
              uploadPercent = Math.round((progressEvent.loaded / progressEvent.total) * 100)
              document.getElementById('percent').textContent = `上传进度 ${uploadPercent}%`
            }
          })
        }
      })
    </script>
  </body>
</html>
